#!/usr/bin/python
#-*-coding:utf-8 -*-
"""
Author:     Shenqt
eMail:      qintaoshen@ubuntukylin.com
Version:    1.0
Protocol:   MIT
introduction:
    这是一款使用了python+webkit+html5技术制作的画图板程序，旨在丰富Ubuntu Kylin上的桌面程序。
    目前是第一个版本，作者水平有限，对画图程序不算很熟悉，程序中有很多Bug，亟待解决。
"""
import gtk
import webkit
import os
import sys
import urllib2
import webbrowser
import copy 
import re
import base64
class webview(webkit.WebView):
    def __init__(self,path,window):
        webkit.WebView.__init__(self);
        self.win = window;
        self.max = False;
        self.settings = self.get_settings();
        self.settings.set_property('enable-file-access-from-file-uris',True);
        self.settings.set_property('enable-universal-access-from-file-uris',True);
        self.settings.set_property('javascript-can-open-windows-automatically',True);
        self.settings.set_property('javascript-can-access-clipboard',True);
        self.settings.set_property('enable-spatial-navigation',True);
        self.settings.set_property('enable-html5-database',True);
        self.settings.set_property('enable-html5-local-storage',True);
        self.settings.set_property('enable-offline-web-application-cache',True);
        self.settings.set_property('enable-universal-access-from-file-uris',True);
        #self.settings.set_property('html5-local-storage-database-path',os.path.abspath(sys.path[0]) + '/FirstPage');
        self.connect('button-press-event',self.button_press_event);
        self.connect('button-release-event',self.button_release_event);
        self.connect('motion-notify-event',self.motion_notify_event);
        self.connect('document-load-finished',self.load_finished);
        self.connect('download-requested',self.down_load);
        self.connect('console-message',self.get_console_message)
        self.set_events( gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK);
                
        #webview open source file
        self.open(path);
        
        #self.execute_script('var footer = document.getElementBy
        
        #ready for drag and move window 
        self.drag = False;
        #top window
        self.top_window = False;
        #max window control
        self.max_press = 0;
    
    def down_load(self,down):
        print "Will download a pic"

    def get_console_message(self,view,message,num,orgin_file):
	    if message == "CloseWindow":
		    gtk.main_quit()
	    if message == "MaxWindow":
	        if self.max is False:
	            self.win.maximize();
	            self.max = True
	        else :
	            self.win.unmaximize();
	            self.max = False
	    if message == "MinWindow":
	        self.win.iconify();
	    if message == "Open File":
	        #此处添加文件选择对话框
	        open_dialog = gtk.FileChooserDialog("画图板-打开", self.win, gtk.FILE_CHOOSER_ACTION_OPEN,
	                                            (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,
	                                            gtk.STOCK_OPEN,gtk.RESPONSE_ACCEPT))
	        open_filter = gtk.FileFilter()
	        open_filter.add_pattern("*.png")
	        open_filter.add_pattern("*.jpeg")
	        open_filter.add_pattern("*.jpg")
	        open_filter.add_pattern("*.bmp")
	        open_dialog.add_filter(open_filter)
	        open_dialog.set_local_only(False)
	        open_dialog.set_modal(True)
	        open_dialog.connect("response",self.open_response_cb)
	        open_dialog.show()
	        pass;
	    if "Save Image:"  in message:
	        #此处获取base64 数据

	        import re 
	        r = re.compile("base64,")
	        self.pic = r.split(message)[1]
	        #print self.pic
	        print len(self.pic)/1024
	        
	        #此处添加路径选择对话框
	        save_dialog = gtk.FileChooserDialog("画图板-保存", self.win, gtk.FILE_CHOOSER_ACTION_SAVE,
	                                    (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,gtk.RESPONSE_ACCEPT))
	        save_dialog.connect("response",self.save_response_cb)
	        save_dialog.show()   


	        
    #when load finished ,close ads
    def load_finished(self,arg1,arg2):
        print "yes"

    def save_response_cb(self,dialog,response_id):
        if response_id == gtk.RESPONSE_ACCEPT:
            uri = dialog.get_filename()
            print "will save " 
            print uri
            dialog.hide()
            picture = open(uri,"wb")
            imgData = base64.b64decode(self.pic)
            picture.write(imgData)
            picture.close()
            #print type(picture)
            r = re.compile('/')
            name = r.split(uri)[-1]
            self.execute_script('$("#name").text("'+name+'")')
        dialog.hide()
    #
    def open_response_cb(self,dialog,response_id):
        open_dialog = dialog
        if response_id == gtk.RESPONSE_ACCEPT:
	        self.file = open_dialog.get_filename()
	        self.file_url = open_dialog.get_uri()
	        print open_dialog.get_uri()
	        #print type(self.file)
	        
	        r = re.compile('/')
	        name = r.split(self.file)[-1]
	        #print name
	        self.execute_script('$("#name").text("'+name+'")')
	        self.execute_script('test("'+self.file_url+'")')
	        self.execute_script('window.changeTitle("'+name+'")')
	        self.execute_script('window.loadImage("'+self.file_url+'")')
        open_dialog.hide()
	    
	    
    #do to drag window 
    def button_press_event(self,widget,event):
        if event.button == 1:
            widget.set_can_focus(True);
            widget.grab_focus();
            self.x,self.y = widget.get_toplevel().get_position();
            if not self.drag and event.y_root - self.y <= 40:
                self.drag = True;        
    def button_release_event(self,widget,event):
        pass

    def motion_notify_event(self,widget,event):
        if self.drag == True:          
            self.w = widget.get_toplevel();
            self.w.begin_move_drag(int(1),int(event.x_root),int(event.y_root),event.time);
            #self.win.set_opacity(0.8);
            self.drag = False;
        else:
            self.win.set_opacity(1.0)
            
#Main GTK window and container                
class browser(gtk.Window):
    def __init__(self,path):
        gtk.Window.__init__(self);
        
        self.view = webview(path,self);
        #self.sw = gtk.ScrolledWindow();
        self.view.open(path);
        #self.sw.add(self.view);
        self.add(self.view);
        
        
        #set window property
        self.set_usize(800,610);
        self.set_title('画图板');
        self.set_resizable(True);
        self.icon = sys.path[0] + '/img/icon.png';
        self.set_icon_from_file(self.icon);
               
        #!new_insert, to set window without border,without decorating
        self.set_decorated(False);
        self.connect("destroy",gtk.main_quit)
        #set position and show window
        self.set_position(gtk.WIN_POS_CENTER);
        self.show_all();
        
        


#HTML files' path could notify out of the class     
path = 'file://' +os.path.abspath(sys.path[0]) + '/index.html';
#path = 'file://' +os.path.abspath(sys.path[0]) + '/frame/0731/index.html';
pic_dict_path = 'file://' + os.path.abspath(sys.path[0]);
youdao = browser(path);
gtk.main();
		

